package cn.itcast.Rainbow_self_mention.Server.Handler;

import android.os.Environment;

import java.io.File;
import java.io.RandomAccessFile;

import RJZ.Rainbow.UserServer.entity.FileEntity.FilePacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class FileUploadServerHandler extends ChannelInboundHandlerAdapter { //继承ChannelInboundHandlerAdapter

    private int byteRead;
    private volatile Long start = 0L;

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    String dirName = "MTZTG";
    File appDir;

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
         appDir= new File(root , dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
          }

    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FilePacket) {
            FilePacket filePacket = (FilePacket) msg;
            byte[] bytes = filePacket.getBytes();
            byteRead = filePacket.getEndPos();
            String md5 = filePacket.getFile_md5();
            String path = appDir + File.separator + md5;
            File file = new File(path);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(start);
            randomAccessFile.write(bytes);
            start = start + byteRead;
            if (byteRead > 0) {
                ctx.writeAndFlush(start);
            } else {
                randomAccessFile.close();
                ctx.channel().parent().close();
            }
        }
        else{
        	super.channelRead(ctx,msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
